﻿using System;
using System.Xml.Linq;

namespace SharePoint.Orm.Caml {
	public class CamlGroupBy {
		public CamlFieldRef First { get; set; }
		public CamlFieldRef Second { get; set; }
		public int? GroupLimit { get; set; }
		public bool Collapse { get; set; }

		public XElement ToXml() {
			XElement groupByElement = new XElement("GroupBy");
			groupByElement.Add(new XAttribute("Collapse", Collapse ? "TRUE" : "FALSE"));
			if (GroupLimit != null) {
				groupByElement.Add(new XAttribute("GroupLimit", GroupLimit.Value));
			}
			groupByElement.Add(First.ToXml());
			if (Second != null) {
				groupByElement.Add(Second.ToXml());
			}
			return groupByElement;
		}

		public static CamlGroupBy Parse(XElement element) {
			CamlGroupBy result = new CamlGroupBy();

			XAttribute collapseAttr = element.Attribute("Collapse");
			if (collapseAttr != null) {
				result.Collapse = bool.Parse(collapseAttr.Value);
			}

			XAttribute groupLimitAttr = element.Attribute("GroupLimit");
			if (groupLimitAttr != null) {
				result.GroupLimit = int.Parse(groupLimitAttr.Value);
			}

			int count = 0;
			foreach (XElement child in element.Elements()) {
				if (count == 0 && child.Name == "FieldRef") {
					result.First = CamlFieldRef.Parse(child);
				} else if (count == 1 && child.Name == "FieldRef") {
					result.Second = CamlFieldRef.Parse(child);
				} else {
					throw new Exception("Unexpected element '" + child.Name + "'");
				}
				count++;
			}

			return result;
		}
	}
}
